#include "clientthread.h"

#include <QFile>


ClientThread::ClientThread(QTcpSocket *client, int r)
{
    clientSocket = client;
    row = r;
}
void ClientThread::run()
{
    // serv接收到client发送的消息，对其进行处理
    connect(clientSocket, &QTcpSocket::readyRead, this, &ClientThread::clientInfoSlot);

}

QDataStream& operator<<(QDataStream& stream, const group_memb& member) {
    stream << member.membname << member.job << member.status << member.img;
    return stream;
}

void ClientThread::clientInfoSlot()
{
    // 先将数据库连接好
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("./my.db");
    if (!db.open()) {
        qDebug() << "Failed to connect to database.";
        return;
    }
    qDebug() << "row 24, my.db connect ok";


    //接收消息
    QDataStream stream(clientSocket); //该代码不会等待

    QString action;
    stream >> action;
    qDebug() << "******************row 32 action is" << action;

    if (action == "LOGIN") { //登录请求
        QString username;
        QString password;
        stream >> username >> password;
        qDebug() << "row 38 username and password is " << username << password;

        // 开始数据库中查找相应的数据
        QSqlQuery query;
        query.prepare("SELECT username, password FROM users WHERE username = :username AND password = :password");
        query.bindValue(":username", username);
        query.bindValue(":password", password);
        query.exec();
        if (query.next()) { // 查到结果了
            // 登录成功, 将用户名记录，以便以后使用。
            qDebug() << "row 49, true";
            stream << true;
            clientname = username;
//            QMap<QString, QTcpSocket*> myMap = Widget::clientMap;
            clientMap.insert(clientname, clientSocket);
            emit returnName(clientname, row); //触发返回给widget用户名的信号，让其能在表格中记录
        }else {
            stream << false;
        }


    } else if (action == "REGISTER") { //注册请求
        QString username;
        QString password;
        stream >> username >> password;

        // 开始向数据库中插入数据
        // 执行插入操作
        QSqlQuery query;
        query.prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
        query.bindValue(":username", username);
        query.bindValue(":password", password);

        if (query.exec()) {
            // 注册成功
            qDebug() << "register success";
            stream << true;
        } else {
            // 注册失败
            qDebug() << "register failed";
            stream << false;
        }
    } else if (action == "CHANGE") { //修改密码请求
        QString username;
        QString oldpass;
        QString newpass;
        stream >> username >> oldpass >> newpass;
        qDebug() << "row 80 username & oldpass & newpass is" << username << oldpass << newpass;

        // 开始查找数据库或者修改
        QString response;
        if (!db.isValid()) {
            qDebug() << "无效的数据库连接";
            response = "ERROR1";
        } else {
            // 2. 执行查询操作
            QSqlQuery query(db);
            query.prepare("SELECT * FROM users WHERE username = :username");
            query.bindValue(":username", username);
            if (query.exec() && query.next()) {
                QString storedPassword = query.value("password").toString();
                if (storedPassword != oldpass) {
                    response = "ERROR2";
                } else {
                    // 3. 更新密码
                    query.prepare("UPDATE users SET password = :newpass WHERE username = :username");
                    query.bindValue(":newpass", newpass);
                    query.bindValue(":username", username);
                    if (query.exec()) {
                        response = "TRUE";
                    } else {
                        qDebug() << "密码更新失败：" << query.lastError().text();
                        response = "ERROR1";
                    }
                }
            } else {
                response = "ERROR1";
            }
        }

        qDebug() << "row 113 response is " << response;
        stream << response;
    } else if (action == "GET_GROUP") { //获得群列表
        // 执行查询语句
        QSqlQuery query;
        query.prepare("SELECT groupname FROM group_member WHERE username = ?");
        query.bindValue(0, clientname);
        query.exec();

        // 检查是否有结果
        if (query.next()) {
            // 发送一个布尔值表示是否找到结果
            bool found = true;
            stream << found;

            // 将数据库中查找到的groupname值逐个发送给客户端
            do {
                QString groupname = query.value(0).toString();
                QByteArray groupimg;
                // 查询groupname的头像
                QString sql = "SELECT groupimg FROM groups WHERE groupname = :groupname";
                QSqlQuery query2;
                query2.prepare(sql);
                query2.bindValue(":groupname", groupname);
                query2.exec();
                // 读取查询结果
                if (query2.next()) {
                    groupimg = query2.value(0).toByteArray();
                } else {
                    qDebug() << "error";
                }
                qDebug() << "row 149 groupname and groupimg.size is " << groupname << groupimg.size();
                stream << groupname << groupimg;
            } while (query.next());

            QString done = "DONE"; // 发送查询结束消息
            stream << done;
        } else {
            // 发送一个布尔值表示未找到结果
            bool found = false;
            stream << found;
        }
    } else if (action == "GET_FRIEND") {
        qDebug() << "row 165 in getFirend";
        // 执行查询语句
        QSqlQuery query;
        query.prepare("SELECT friendname FROM friendship WHERE username = ?");
        query.bindValue(0, clientname);
        query.exec();

        // 检查是否有结果
        if (query.next()) {
            // 发送一个布尔值表示是否找到结果
            bool found = true;
            stream << found;

            // 将数据库中查找到的groupname值逐个发送给客户端
            do {
                QString friendname = query.value(0).toString();
                QByteArray friendimg;
                // 查询groupname的头像
                QString sql = "SELECT userimg FROM users WHERE username = :username";
                QSqlQuery query2;
                query2.prepare(sql);
                query2.bindValue(":username", friendname);
                query2.exec();
                // 读取查询结果
                if (query2.next()) {
                    friendimg = query2.value(0).toByteArray();
                } else {
                    qDebug() << "error";
                }
                qDebug() << "row 149 groupname and groupimg.size is " << friendname << friendimg.size();
                stream << friendname << friendimg;
            } while (query.next());

            QString done = "DONE"; // 发送查询结束消息
            stream << done;
        } else {
            // 发送一个布尔值表示未找到结果
            bool found = false;
            stream << found;
        }
    } else if (action == "GET_IMG") {

        QString username;
        stream >> username;
        qDebug() << "row 151 username is " << username;
        QByteArray imageData; // 用于存储图像数据的字节数组

        // 执行 SQLite 数据库操作
        QSqlQuery query;
        query.prepare("SELECT userimg FROM users WHERE username = :username");
        query.bindValue(":username", username); // username 是您的变量，用于匹配要查询的记录

        if (query.exec() && query.next()) {
            stream << true;
            qDebug() << "row 160 in query.exec";
            imageData = query.value(0).toByteArray(); // 获取查询结果中的图像数据
        } else {
            stream << false;
            qDebug() << "Failed to retrieve image data from the database:" << query.lastError().text();
        }
        // 将图像数据发送出去
        stream << imageData; // 将图像数据写入流中
    } else if (action == "UPDATE_IMG") {
        QByteArray img;
        stream >> img;
        qDebug() << "row 171 get img, size is " << img.size();

        QSqlQuery query;
        QString updateQuery = QString("UPDATE users SET userimg = :img WHERE username = :name");
        query.prepare(updateQuery);
        query.bindValue(":img", img);
        query.bindValue(":name", clientname);

        // 执行更新操作
        if (query.exec()) {
            qDebug() << "row 182 User image updated successfully.";
        } else {
            qDebug() << "Failed to update user image:" << query.lastError().text();
        }
    } else if (action == "SEND_MSG_GROUP") {
        QString groupname;
        QString msg;
        QString whoSend;
        QByteArray whoSendImg;
        stream >> groupname;
        stream >> msg;
        stream >> whoSend >> whoSendImg;

        qDebug() << "row 206 groupname and msg is " << groupname << msg;
        qDebug() << "row 212 clientMap is " << clientMap;
        qDebug() << "keys of clientMap" << clientMap.keys();

        // 查询whoSend是否被禁言，如果被禁弹窗报错
        QSqlQuery query1;
        query1.prepare("SELECT * FROM group_member WHERE groupname = :groupName AND username = :whoSend");
        query1.bindValue(":groupName", groupname);
        query1.bindValue(":whoSend", whoSend);

        if (query1.exec() && query1.first()) {
            QString status = query1.value("status").toString();
            if (status == "已禁言") {
                bool isInhibit = true;
                QString action = "ISINHIBIT";
                stream << action << isInhibit;
                return;
            } else {
                bool isInhibit = false;
                QString action = "ISINHIBIT";
                stream << action << isInhibit;
            }
        } else {
            qDebug() << "Failed to execute query:" << query1.lastError().text();
        }


        // 打印QMap值，使用迭代器遍历 QMap。（能打印成功）
        for (auto &key : clientMap.keys()) {
            qDebug() << key << ": " << clientMap[key];
        }

//        QMap<QString, QTcpSocket*>::const_iterator it;
//        for (it = myMap.constBegin(); it != myMap.constEnd(); ++it) {
//            QString key = it.key();
//            QTcpSocket* socket = it.value();
//            qDebug() << "row 214 Key:" << key << ", Socket:" << socket;
//        }

        // 去数据库中查找群组中的所有成员，并查看其是否在线，在线就将消息发送给他们
        // 执行 SQL 查询语句
        QString queryStr = QString("SELECT * FROM group_member WHERE groupname = '%1'").arg(groupname);
        QSqlQuery query;
        if (query.exec(queryStr)) {
            while (query.next()) {
                QString username = query.value("username").toString(); // username变量第一次出现
                // 检查 username 是否存在于 clientMap 变量的键中
                if (username != whoSend && clientMap.contains(username)) {
                    // 执行相应的操作
                    QTcpSocket* socket2 = clientMap.value(username);
                    QDataStream stream2(socket2);
                    QString action = "GROUP_MSG";
                    stream2 << action;
                    stream2 << groupname << msg;
                    stream2 << whoSend << whoSendImg;
                }
            }
        } else {
            // 查询执行失败
            qDebug() << "Query failed: " << query.lastError().text();
        }
    } else if (action == "SEND_MSG_FRIEND") {
        QString whoGet;
        QString msg;
        QString whoSend;
        QByteArray whoSendImg;
        stream >> whoGet;
        stream >> msg;
        stream >> whoSend >> whoSendImg;

        qDebug() << "row 299 whoGet and msg is " << whoGet << msg;
        qDebug() << "row 300 clientMap is " << clientMap;
        qDebug() << "keys of clientMap" << clientMap.keys();
        // 打印QMap值，使用迭代器遍历 QMap。（能打印成功）
        for (auto &key : clientMap.keys()) {
            qDebug() << key << ": " << clientMap[key];
        }

        // 回应对方是否在线
//        QString action = "RESPONSE";
//        stream << action;
//        bool response;
        if (clientMap.contains(whoGet)) {
//            response = true;
//            stream << response; // 返回真
            clientSocket->flush();

            QTcpSocket* socket2 = clientMap.value(whoGet);
            QDataStream stream2(socket2);
            QString action = "FRIEND_MSG";
            stream2 << action;
            stream2 << whoGet << msg;
            stream2 << whoSend << whoSendImg;
        } else {
//            response = false;
//            stream << response;
//            clientSocket->flush();
        }
//        qDebug() << "row 319 response is" << response;

    } else if (action == "GROUP_MEB_LIST") {
        qDebug() << "row 328 action is " << action;
        QString groupname;
        stream >> groupname;
        QList<group_memb> membersList;  // 创建 group_memb 结构体的列表

        QSqlQuery query;
        query.prepare("SELECT username, job, status FROM group_member WHERE groupname = :groupname "
                      "ORDER BY CASE WHEN job = '群主' THEN 1 "
                      "              WHEN job = '管理员' THEN 2 "
                      "              ELSE 3 END, job ASC");

        query.bindValue(":groupname", groupname);

        if (query.exec()) {
            // 遍历查询结果
            bool response = true;
//            stream << response;
            QList<group_memb> membersList;  // 创建 group_memb 结构体的列表
            membersList.clear();
            group_memb memb;
            QByteArray img;
            while (query.next()) {
                QString username = query.value("username").toString();
                QString job = query.value("job").toString();
                QString status = query.value("status").toString();

                // 查询groupname的头像
                QString sql = "SELECT userimg FROM users WHERE username = :username";
                QSqlQuery query2;
                query2.prepare(sql);
                query2.bindValue(":username", username);
                query2.exec();
                // 读取查询结果
                if (query2.next()) {
                    img = query2.value(0).toByteArray();
                } else {
                    qDebug() << "error";
                }
                qDebug() << "row 396 groupname and groupimg.size is " << username << img.size();

//                // 将姓名和职位信息发送给客户端
//                stream << username;
//                stream << img << job << status;
                // 将结果保存到结构体数组中
                memb.membname = username;
                memb.job = job;
                memb.status = status;
                memb.img = img;
                membersList.append(memb);

            }
            stream << response << membersList;
//            QString done = "DONE";
//            stream << done;
            qDebug() << "row 372, send done";
        } else {
            // 查询执行失败
            bool response = false;
            stream << response;
            qDebug() << "查询失败：" << query.lastError().text();
        }

    } else if (action == "INHIBIT") {
        qDebug() << "row 395 action is " << action;
        QString membname;
        QString groupname;
        stream >> groupname >> membname;
        qDebug() << "get groupname and membname" << groupname << membname;

        QSqlQuery query;
        QString sql = "UPDATE group_member SET status = '已禁言' WHERE groupname = :groupname AND username = :username";
        query.prepare(sql);
        query.bindValue(":groupname", groupname);
        query.bindValue(":username", membname);
        if (!query.exec()) {
            qDebug() << "Failed to execute query:" << query.lastError().text();
        } else {
            qDebug() << "Update successful!";
        }
    } else if (action == "DISINHIBIT") {
        qDebug() << "row 412 action is " << action;
        QString membname;
        QString groupname;
        stream >> groupname >> membname;
        qDebug() << "get groupname and membname" << groupname << membname;

        QSqlQuery query;
        QString sql = "UPDATE group_member SET status = '正常' WHERE groupname = :groupname AND username = :username";
        query.prepare(sql);
        query.bindValue(":groupname", groupname);
        query.bindValue(":username", membname);
        if (!query.exec()) {
            qDebug() << "Failed to execute query:" << query.lastError().text();
        } else {
            qDebug() << "Update successful!";
        }
    } else if (action == "DELETE_MEMB") {
        qDebug() << "row 431, delete action" << action;
        QString membname;
        QString groupname;
        stream >> groupname >> membname;
        QSqlQuery query;
        query.prepare("DELETE FROM group_member WHERE groupname = :groupName AND username = :memberName");
        query.bindValue(":groupName", groupname);
        query.bindValue(":memberName", membname);
        if (query.exec()) {
            // 执行成功
            qDebug() << "row 466 delete success";
        } else {
            // 执行失败
            qDebug() << "Failed to delete data:" << query.lastError().text();
        }

    } else if (action == "SEND_FILE_FRIEND") {
        qDebug() << "row 472 gey aciton is " << action;
        QString whoSend;
        QString whoGet;
        stream >> whoSend >> whoGet;
        qDebug() << "whoSend and whoGet is " << whoSend << whoGet;
        QByteArray fileArray;
        QString fileName;
        stream >> fileName;
//        stream >> fileArray;

        quint32 fileSize;
        stream >> fileSize;  // 接收文件数据的大小
//        QByteArray fileData;
        fileArray.resize(fileSize);
//        stream >> fileArray;
        stream.readRawData(fileArray.data(), fileSize);  // 接收文件数据
//        fileArray = clientSocket->readAll();  // 从套接字中读取所有可用的数据

        qDebug() << "row 478 fileArray size is " << fileArray.size();

        // 查看对方是否在线
        if (clientMap.contains(whoGet)) {
//            response = true;
//            stream << response; // 返回真
//            clientSocket->flush();
            QTcpSocket* socket2 = clientMap.value(whoGet);
            QDataStream stream2(socket2);
            QString action2 = "FRIEND_FILE";
            stream2 << action2;
            stream2 << fileName;
            stream2 << fileSize;
            stream2.writeRawData(fileArray.constData(), fileSize);  // 接收文件数据

//            stream2 << fileArray;
        } else {
//            response = false;
//            stream << response;
//            clientSocket->flush();
        }

    }


}

